/**
 * 佣金管理服务
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    require("pagination");
    var util = require("util");
    var angular = require("angular");

    var mainModule = angular.module('mainModule', []);

    // 统一查询服务
    function queryService($http, $q, baseData) {
        var service = {
            data: [],
            hasData: true,
            checkAll: false,
            pageIndex: 1,

            // 全选/取消全选
            updateCheckAll: function () {
                for (var i = 0; i < service.data.length; i++) {
                    service.data[i].checked = service.checkAll;
                }
            },

            // 同步全选/取消全选
            updateCheck: function (record) {
                var checked = true;
                for (var i = 0; i < service.data.length; i++) {
                    if (!service.data[i].checked) {
                        checked = false;
                        break;
                    }
                }

                service.checkAll = checked;
            },

            // 导出
            exportData: function (filters) {
                if (!baseData.projectId) {
                    return;
                    }

                filters = service.getFilters(filters);
                delete filters.page_index;
                delete filters.page_size;
                var url = '/api/index.php?r=qmyx/payment-manage/authorize-export-excel';
                url += '&filter=' + encodeURIComponent(JSON.stringify(filters));
                url += '&token=' + util.getToken();
                window.location.href = url;
            },

            // 导入
            importData: function () {

            },

            getFilters: function (filters) {
                filters = filters || {};
                filters.proj_id = baseData.projectId;
                filters.page_size = service.pageSize;
                filters.type = baseData.brokerageState - 1;

                return filters;
            },

            doQuery: function (filters, pageIndex) {
                filters = service.getFilters(filters);
                filters.page_index = pageIndex || 1;
                var url = '/api/index.php?r=qmyx/payment-manage/get-authorize-pay-list';


                if (arguments.callee.canceller) {
                    // 如果查询时，前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, { filter: filters }, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.data = data.data.data;
                        service.total = data.data.total;
                        service.checkAll = false;
                        service.hasData = !!service.data.length;
                        service.pageIndex = filters.page_index;
                    });
            }
        };

        return service;
    }
    mainModule.factory('query', ['$http', '$q', 'baseData', queryService]);

    // 过滤条件服务
    function filterService($http, query, baseData) {
        var service = {
            // 起始时间
            startDate: '',
            // 结束时间
            endDate: '',

            query: function (pageIndex) {
                if (!baseData.projectId) {
                    return;
                    }

                baseData.currentQueryService = service;
                query.doQuery(service.getFilters(), pageIndex);
            },

            exportData: function () {
                query.exportData(service.getFilters());
            },

            getFilters: function() {
                var filters = {};

                if (baseData.payTypeList && baseData.payTypeList.length) {
                    var payTypeList = [];
                    for (var i = 0; i < baseData.payTypeList.length; i++) {
                        if (baseData.payTypeList[i].checked) {
                            payTypeList.push(baseData.payTypeList[i].text);
                        }
                    }
                    filters['pay_type_list'] = payTypeList;
                }

                filters['created_on_from'] = service.startDate;
                filters['created_on_to'] = service.endDate;

                return filters;
            },

            // 撤销过滤
            clearFilter: function () {
                for (var i = 0; i < baseData.payTypeList.length; i++) {
                    baseData.payTypeList[i].checked = false;
                }
                baseData.payTypeListCheckedAll = false;
                service.startDate = '';
                service.endDate = '';
            }
        };

        return service;
    }
    mainModule.factory('filter', ['$http', 'query', 'baseData', filterService]);

    // 简单查询服务
    function searchSerivce(query, baseData) {
        var service = {
            fieldList: [
                { value: 'serial_number', text: '流水号' },
                { value: 'account_number', text: '银行账号' }
            ],
            // 查询字段
            field: 'serial_number',
            // 关键字
            keyword: '',

            getFilters: function () {
                var filters = {};
                filters[service.field] = service.keyword;
                return filters;
            },

            query: function (pageIndex) {
                if (!baseData.projectId) {
                    return;
                }

                baseData.currentQueryService = service;
                query.doQuery(service.getFilters(), pageIndex);
            },

            exportData: function () {
                query.exportData(service.getFilters());
            }
        };

        return service;
    }
    mainModule.factory('search', ['query', 'baseData', searchSerivce]);

    // 基础数据服务（项目列表、经纪人身份等）
    function baseDataService($http, $q) {
        var service = {
            // 基础数据是否加载
            loaded: false,
            // 支付类型列表
            payTypeList: [
                { text: '代理佣金费', checked: false },
                { text: '媒介广告费', checked: false },
                { text: '推广活动费', checked: false },
                { text: '策划咨询费', checked: false },
                { text: '物料制作费', checked: false }
            ],
            // 支付类型全选
            payTypeListCheckedAll: false,
            // 项目列表
            projectList: [],
            // 当前查询服务（search、filter）
            currentQueryService: null,
            // 佣金类型
            brokerageType: -1,
            // 佣金状态
            brokerageState: -1,

            // 统一查询
            query: function (pageIndex) {
                if (service.currentQueryService) {
                    service.currentQueryService.query(pageIndex);
                }
            },

            // 统一导出，使用查询的结果
            exportData: function () {
                if (service.currentQueryService) {
                    service.currentQueryService.exportData();
                }
            },

            // 全选/取消全选
            updatePayTypeListCheckedAll: function () {
                for (var i = 0; i < service.payTypeList.length; i++) {
                    service.payTypeList[i].checked = service.payTypeListCheckedAll;
                }
            },

            // 同步全选/取消全选
            updatePayTypeListChecked: function () {
                var checked = true;
                for (var i = 0; i < service.payTypeList.length; i++) {
                    if (!service.payTypeList[i].checked) {
                        checked = false;
                        break;
                    }
                }

                service.payTypeListCheckedAll = checked;
            },

            // 初始化查询表单数据
            initData: function () {
                var promises = [
                    // 项目列表
                    $http.get('/api/index.php?r=qmyx/customer-manage/get-project-list')
                ];

                return $q.all(promises).then(function (xhrs) {
                    var i = 0;
                    service.projectList = xhrs[i++].data.data;

                    service.loaded = true;
                });
            }
        };

        return service;
    }
    mainModule.factory('baseData', ['$http', '$q', baseDataService]);

    function toolbarSerivce($http, $filter, baseData, query) {
        var service = {
            // 执行审定
            approve: function (record) {
                var data = {
                    oid: record.b_authorize_payId
                };

                var url = '/api/index.php?r=qmyx/payment-manage/authorize-audit';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 显示批量审定
            showBatchApprove: function () {
                var batchApproveData = [];
                var totalAmount = 0;

                for (var i = 0; i < query.data.length; i++) {
                    var record = query.data[i];
                    if (record.checked) {
                        totalAmount += parseFloat(record.amount) || 0;
                        batchApproveData.push(record.b_authorize_payId);
                    }
                }

                if (batchApproveData.length) {
                    var msg = '您批量审核 ' + batchApproveData.length + ' 笔委托，付款总额 ' + $filter('number')(totalAmount) + ' 元';
                    util.confirm(msg, {
                        ok: function () {
                            service.batchApprove(batchApproveData);
                        }
                    });
                } else {
                    util.alert('请选择要操作的记录');
                }
            },

            // 执行批量审定
            batchApprove: function (batchApproveData) {
                var data = {
                    oids: batchApproveData
                };
                var url = '/api/index.php?r=qmyx/payment-manage/authorize-audit-batch';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 删除记录
            deleteRecord: function(record) {
                var data = {
                    oid: record.b_authorize_payId
                };

                var url = '/api/index.php?r=qmyx/payment-manage/authorize-delete';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 新增付款委托
            addEntrustPay: function (record) {
                var data = {
                    proj_id: baseData.projectId,
                    authorize_pay: record
                };

                var url = '/api/index.php?r=qmyx/payment-manage/add-authorize-pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 取消审定
            cancelApprove: function (record) {
                var data = {
                    oid: record.b_authorize_payId
                };

                var url = '/api/index.php?r=qmyx/payment-manage/authorize-un-audit';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 显示批量委托发放
            showBatchPay: function () {
                var data = [];
                var totalAmount = 0;
                for (var i = 0; i < query.data.length; i++) {
                    var record = query.data[i];
                    if (record.checked) {
                        totalAmount += parseFloat(record.amount) || 0;
                        data.push(record.b_authorize_payId);
                    }
                }

                if (data.length) {
                    util.confirm('您批量委托发放 ' + data.length + ' 笔，付款总额 ' + $filter('number')(totalAmount) + ' 元', {
                        ok: function () {
                            service.batchPay(data);
                        }
                    });
                } else {
                    util.alert('请选择要操作的记录');
                }
            },

            // 执行批量委托发放
            batchPay: function(oids) {
                var data = {
                    oids: oids
                };
                var url = '/api/index.php?r=qmyx/payment-manage/authorize-pay-batch';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },

            // 委托发放
            pay: function (record) {
                var data = {
                    oid: record.b_authorize_payId
                };

                var url = '/api/index.php?r=qmyx/payment-manage/authorize-pay';
                return $http.post(url, data).then(function () {
                    baseData.query();
                });
            },
        };

        return service;
    }
    mainModule.factory('toolbar', ['$http', '$filter', 'baseData', 'query', toolbarSerivce]);
    
    module.exports = mainModule;
});